<?php

namespace app\admin\controller;

use app\common\model\user\BabycarUser as BabycarUserModel;

/**
 * TP Babycar 用户管理
 */
class BabycarUser extends Controller
{
    /**
     * 用户列表
     * @return \think\response\Json
     */
    public function list()
    {
        $params = $this->request->param();
        
        // 验证分页参数
        $page = isset($params['page']) ? intval($params['page']) : 1;
        $page = max(1, $page);
        
        $model = new BabycarUserModel();
        $list = $model->getList($params);
        
        return json(['code' => 0, 'msg' => 'success', 'data' => $list]);
    }

    /**
     * 用户详情
     * @param int $user_id 用户ID
     * @return \think\response\Json
     */
    public function detail($user_id)
    {
        $model = new BabycarUserModel();
        $detail = $model->getDetail($user_id);
        if (!$detail) {
            return json(['code' => 1, 'msg' => '用户不存在']);
        }
        return json(['code' => 0, 'msg' => 'success', 'data' => $detail]);
    }

    /**
     * 更新用户信息
     * @param int $user_id 用户ID
     * @return \think\response\Json
     */
    public function update($user_id)
    {
        $data = $this->request->post();
        
        // 验证手机号格式
        if (isset($data['mobile']) && !preg_match('/^1[3-9]\d{9}$/', $data['mobile'])) {
            return json(['code' => 1, 'msg' => '手机号格式不正确']);
        }

        // 验证性别值
        if (isset($data['gender']) && !in_array($data['gender'], [0, 1, 2])) {
            return json(['code' => 1, 'msg' => '性别值不正确']);
        }

        $model = new BabycarUserModel();
        $result = $model->updateUser($user_id, $data);
        if (!$result) {
            return json(['code' => 1, 'msg' => '更新失败']);
        }
        return json(['code' => 0, 'msg' => '更新成功']);
    }

    /**
     * 删除用户
     * @param int $user_id 用户ID
     * @return \think\response\Json
     */
    public function delete($user_id)
    {
        $model = new BabycarUserModel();
        $result = $model->deleteUser($user_id);
        if (!$result) {
            return json(['code' => 1, 'msg' => '删除失败，用户可能不存在或已被删除']);
        }
        return json(['code' => 0, 'msg' => '删除成功']);
    }
} 